/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package applety;

import data.Data;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
 *
 * @author Riso
 */
public class hra5 extends javax.swing.JApplet implements Runnable {

    Thread vlakno;
    boolean ide = true;
    boolean nacitane = false;
    int body = 0;
    boolean skontrolovane = false;
    String id;
    /**
     * Initializes the applet hra5
     */
    int[] vysledky = new int[6];

    private void nacitajData(Data data) {
        JLabel[] cislaz = {
            jLabel13,
            jLabel15,
            jLabel17,
            jLabel18,
            jLabel20
        };
        JLabel[] cisla = {
            jLabel12,
            jLabel14,
            jLabel16
        };
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 5; i++) {
            sb.append(cislaz[i].getText() + ";");
        }
        for (int i = 0; i < 3; i++) {
            sb.append(cisla[i].getText() + ";");
        }
        sb.append(jTextField1.getText() + ";");
        sb.append(jTextField2.getText() + ";");
        sb.append(jTextField3.getText() + ";");
        for (int i = 0; i < 6; i++) {
            sb.append(vysledky[i] + ";");
        }
        data.string1 = data.typ+";"+sb.toString();
    }

    private void nacitaj() {
        jLabel21.setText("");
        jLabel22.setText("");
        jLabel23.setText("");
        jTextField1.setText("");
        jTextField2.setText("");
        jTextField3.setText("");
        JLabel[] cislaz = {
            jLabel13,
            jLabel15,
            jLabel17,
            jLabel18,
            jLabel20
        };
        JLabel[] cisla = {
            jLabel12,
            jLabel14,
            jLabel16
        };
        vysledky[0] = (int) (20 * Math.random() + 20);
        for (int i = 0; i < cislaz.length; i++) {
            int n = 0;
            StringBuilder s = new StringBuilder();
            int z = (int) (2 * Math.random() + 1);
            if (z == 1) {
                s.append("+");
                n = (int) (20 * Math.random() + 1);
                vysledky[i + 1] = vysledky[i] + n;
            } else {
                s.append("-");
                n = (int) (20 * Math.random() + 1);
                vysledky[i + 1] = vysledky[i] - n;
            }
            s.append(n);
            cislaz[i].setText(s.toString());
        }
        jLabel12.setText(vysledky[0] + "");
        jLabel14.setText(vysledky[2] + "");
        jLabel16.setText(vysledky[4] + "");
    }

    @Override
    public void init() {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(hra5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(hra5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(hra5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(hra5.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the applet
         */
        vlakno = new Thread(this);
        this.setSize(500, 240);
        initComponents();
        nacitaj();
        vlakno.start();
    }

    /**
     * This method is called from within the init() method to initialize the
     * form. WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel19 = new javax.swing.JLabel();
        jTextField3 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField1 = new javax.swing.JTextField();
        jLabel12 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        jLabel16 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel13 = new javax.swing.JLabel();
        jLabel15 = new javax.swing.JLabel();
        jLabel17 = new javax.swing.JLabel();
        jLabel18 = new javax.swing.JLabel();
        jLabel20 = new javax.swing.JLabel();
        jLabel21 = new javax.swing.JLabel();
        jLabel22 = new javax.swing.JLabel();
        jLabel23 = new javax.swing.JLabel();
        jLabel24 = new javax.swing.JLabel();

        jLabel19.setText("jLabel19");

        setMaximumSize(new java.awt.Dimension(500, 200));
        setMinimumSize(new java.awt.Dimension(500, 200));
        setPreferredSize(new java.awt.Dimension(500, 200));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTextField3.setBackground(new java.awt.Color(240, 240, 240));
        jTextField3.setText("20");
        jTextField3.setOpaque(false);
        getContentPane().add(jTextField3, new org.netbeans.lib.awtextra.AbsoluteConstraints(127, 86, 27, 25));

        jTextField2.setText("20");
        jTextField2.setOpaque(false);
        getContentPane().add(jTextField2, new org.netbeans.lib.awtextra.AbsoluteConstraints(267, 86, 27, 25));

        jTextField1.setText("20");
        jTextField1.setOpaque(false);
        getContentPane().add(jTextField1, new org.netbeans.lib.awtextra.AbsoluteConstraints(406, 86, 27, 25));

        jLabel12.setText("20");
        getContentPane().add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(64, 93, 20, 15));

        jLabel14.setText("20");
        getContentPane().add(jLabel14, new org.netbeans.lib.awtextra.AbsoluteConstraints(204, 93, 20, 15));

        jLabel16.setText("20");
        getContentPane().add(jLabel16, new org.netbeans.lib.awtextra.AbsoluteConstraints(344, 93, 20, 15));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/kruh.png"))); // NOI18N
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(50, 80, -1, -1));

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/kruh.png"))); // NOI18N
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 80, -1, -1));

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/kruh.png"))); // NOI18N
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 80, -1, -1));

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/kruh.png"))); // NOI18N
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 80, -1, -1));

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/kruh.png"))); // NOI18N
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 80, -1, -1));

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/kruh.png"))); // NOI18N
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 80, -1, -1));

        jLabel7.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/sipka.png"))); // NOI18N
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 40, -1, -1));

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/sipka.png"))); // NOI18N
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 40, -1, -1));

        jLabel9.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/sipka.png"))); // NOI18N
        getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 40, -1, -1));

        jLabel10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/sipka.png"))); // NOI18N
        getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 40, -1, -1));

        jLabel11.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/sipka.png"))); // NOI18N
        getContentPane().add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(300, 40, -1, -1));

        jButton1.setText("Nová hra");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 170, 80, -1));

        jButton2.setText("Skontroluj");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 140, -1, -1));

        jLabel13.setText("jLabel13");
        getContentPane().add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 40, 50, -1));

        jLabel15.setText("jLabel15");
        getContentPane().add(jLabel15, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 40, 50, -1));

        jLabel17.setText("jLabel17");
        getContentPane().add(jLabel17, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 40, 50, -1));

        jLabel18.setText("jLabel18");
        getContentPane().add(jLabel18, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 40, 50, -1));

        jLabel20.setText("jLabel20");
        getContentPane().add(jLabel20, new org.netbeans.lib.awtextra.AbsoluteConstraints(360, 40, 50, -1));
        getContentPane().add(jLabel21, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 120, 40, 20));
        getContentPane().add(jLabel22, new org.netbeans.lib.awtextra.AbsoluteConstraints(260, 120, 40, 20));
        getContentPane().add(jLabel23, new org.netbeans.lib.awtextra.AbsoluteConstraints(400, 120, 40, 20));

        jLabel24.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pic/animated-gifs-simpsons-049.gif"))); // NOI18N
        jLabel24.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel24MouseClicked(evt);
            }
        });
        getContentPane().add(jLabel24, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 140, 140, 100));
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        nacitaj();
        skontrolovane = false;
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // Skontrolujeme správnosť odpovedí
        if (skontrolovane == true) {
            JOptionPane.showMessageDialog(rootPane, "Tento pokus je už skontrolovaný. Klikni na 'Nové Úlohy'");
            return;
        }
        try {
            if (Integer.parseInt(jTextField3.getText()) == vysledky[1]) {
                body++;
                jLabel21.setText("ok");
            } else {

                jLabel21.setText("chyba");
            }
            //dalšia odpoveď
            if (Integer.parseInt(jTextField2.getText()) == vysledky[3]) {
                body++;
                jLabel22.setText("ok");
            } else {
                jLabel22.setText("chyba");
            }
            //dalšia odpoveď
            if (Integer.parseInt(jTextField1.getText()) == vysledky[5]) {
                body++;
                jLabel23.setText("ok");
            } else {

                jLabel23.setText("chyba");
            }

            skontrolovane = true;
            zapisBody();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Všetky polia musia byť vyplnené a odpoveď môže obsahovať len čísla.");
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jLabel24MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel24MouseClicked
        // TODO add your handling code here:
        jLabel24.setVisible(false);
        
    }//GEN-LAST:event_jLabel24MouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    private javax.swing.JLabel jLabel19;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel20;
    private javax.swing.JLabel jLabel21;
    private javax.swing.JLabel jLabel22;
    private javax.swing.JLabel jLabel23;
    private javax.swing.JLabel jLabel24;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration//GEN-END:variables

    private void zapisData(String data) {
        String d = data;
        if (d.length() != 1 && d.substring(0, 2).equals("5;")) {
            d = d.substring(2);
            System.out.println(d);
            JLabel[] cislaz = {
                jLabel13,
                jLabel15,
                jLabel17,
                jLabel18,
                jLabel20
            };
            JLabel[] cisla = {
                jLabel12,
                jLabel14,
                jLabel16
            };
            
            for (int i = 0; i < 5; i++) {
                cislaz[i].setText(d.substring(0, d.indexOf(";")));
                d = d.substring(d.indexOf(";")+1);
            }
            for (int i = 0; i < 3; i++) {
                cisla[i].setText(d.substring(0, d.indexOf(";")));
                d = d.substring(d.indexOf(";")+1);
            }
            jTextField1.setText(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";")+1);
            jTextField2.setText(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";")+1);
            jTextField3.setText(d.substring(0, d.indexOf(";")));
            d = d.substring(d.indexOf(";")+1);
            for (int i = 0; i < 6; i++) {
                vysledky[i] = Integer.parseInt(d.substring(0, d.indexOf(";")));
                d = d.substring(d.indexOf(";")+1);
            }
        }
    }

    private synchronized void zapisBody() {
        try {

            URL servlet = new URL("http://localhost:8080/Portalpredeti/zapisBody");
            URLConnection con = servlet.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setUseCaches(false);
            con.setRequestProperty("Content-Type", "application/x-java-serialized-object");

            OutputStream outstream = con.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outstream);
            oos.writeObject("5"); //cislo ulohy
            oos.writeObject(id);
            oos.writeObject(body + "/" + "3");
            body = 0;
            oos.flush();
            oos.close();

            InputStream instr = con.getInputStream();
            ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
            String s = (String) inputFromServlet.readObject();
            inputFromServlet.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            while (ide) {
                Data d = new Data(5);
                if (!skontrolovane) {
                    nacitajData(d);
                }
                URL servlet = new URL("http://localhost:8080/Portalpredeti/zapisDoDB");
                URLConnection con = servlet.openConnection();
                con.setDoOutput(true);
                con.setDoInput(true);
                con.setUseCaches(false);
                con.setRequestProperty("Content-Type", "application/x-java-serialized-object");
                id = getParameter("ID");
                // TODO: toto ID na konci zmazať
                //id = "1";
                if (!nacitane) {
                    OutputStream outstream = con.getOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(outstream);
                    oos.writeObject("nacitat");

                    oos.writeObject(id);
                    oos.writeObject(d);
                    oos.flush();
                    oos.close();

                    InputStream instr = con.getInputStream();
                    ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
                    String s = (String) inputFromServlet.readObject();
                    if (s != null) {
                        zapisData(s);
                    }
                    inputFromServlet.close();
                    repaint();
                    nacitane = true;
                } else if (!skontrolovane) {
                    OutputStream outstream = con.getOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(outstream);
                    oos.writeObject("zapis");

                    oos.writeObject(id);
                    oos.writeObject(d);
                    oos.flush();
                    oos.close();
                    InputStream instr = con.getInputStream();
                    ObjectInputStream inputFromServlet = new ObjectInputStream(instr);
                    String c = (String) inputFromServlet.readObject();
                    System.out.println(c);
                    inputFromServlet.close();

                }
                vlakno.sleep(10000);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

    }
}
